package com.jh.microservice.base;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.support.GenericApplicationContext;

/**
 * @author Administrator
 * @projectName newforward
 * @title
 * @package com.jh.microservice.base
 * @description
 * @date 2019/7/27 16:04
 */
public class SpringEventListenerDemo {

    public static void main(String[] args) {
        GenericApplicationContext context = new GenericApplicationContext();

        // 添加监听器
        // context.addApplicationListener(new ClosedListener());
        context.addApplicationListener(new AllEventListener());
        /*context.addApplicationListener(event -> {
            System.err.println("监听事件：" + event);
            System.out.println(event.getSource());
        });*/

        // 启动Spring应用上下文
        context.refresh();

        // Spring应用上下文发布事件
        context.publishEvent("HelloWorld");

        // 自定义事件
        context.publishEvent(new MyEvent("custom event"));

        // 关闭上下文
        context.close();
    }

    private static class AllEventListener implements ApplicationListener{

        @Override
        public void onApplicationEvent(ApplicationEvent event) {
            System.err.println("Event：" + event);
        }
    }

    private static class ClosedListener implements ApplicationListener<ContextClosedEvent> {

        @Override
        public void onApplicationEvent(ContextClosedEvent event) {
            System.out.println("关闭了");
        }
    }

    private static class MyEvent extends ApplicationEvent{

        /**
         * Create a new ApplicationEvent.
         *
         * @param source the object on which the event initially occurred (never {@code null})
         */
        public MyEvent(Object source) {
            super(source);
        }

    }

}
